package com.ibiaoke.boss.service;


import com.ibiaoke.common.cache.EhCacheKit;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.utils.*;
import com.ibiaoke.customer.dao.CustomerDao;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.marketing.service.CouponReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * Created by huhaichao on 2017/6/6.
 */
@Service("loginService")

public class LoginServiceImpl implements LoginService {

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private RegisterService registerService;

    @Autowired
    private CouponReceiveService couponReceiveService;

    @Override
    public Customer login(String userName, String password) {

        AssertUtils.notBlank(userName, "用户名不能为空");
        AssertUtils.notBlank(password, "密码不能为空");

        Customer user;
        if (ValidateUtils.isMobile(userName)) {
            user = customerDao.getByMobile(userName);
        } else {
            user = customerDao.getByName(userName);
        }

        AssertUtils.notNull(user, "用户不存在");

        String md5Password = MD5Utils.getMD5String(password, user.getUserSalt());
        AssertUtils.requireEquals(md5Password, user.getCustomerPassword(), "用户名或密码错误");

        boolean update=StringUtils.isEmpty(user.getToken()) || user.getTokenExpireTime()==null
                ||new Date().after(user.getTokenExpireTime());
        if (update) {
            user.setToken(UUID.randomUUID().toString());
            user.setTokenExpireTime(DateUtils.add(Calendar.MONTH, 2));
            customerDao.updateByPrimaryKey(user);
        }
        return user;
    }

    @Override
    public Customer loginByMobileVerify(String mobile, String code) {
        SmsUtil.validateMobileCode(mobile,code);
        Customer user = customerDao.getByMobile(mobile);
        if (user == null) {//未注册的新用户
            registerService.createNewCustomer(mobile, null);
        }
        user = customerDao.getByMobile(mobile);
        boolean update=StringUtils.isEmpty(user.getToken()) || user.getTokenExpireTime()==null
                ||new Date().after(user.getTokenExpireTime());
        if (update) {
            user.setToken(UUID.randomUUID().toString());
            user.setTokenExpireTime(DateUtils.add(Calendar.MONTH, 2));
            customerDao.updateByPrimaryKey(user);
        }
        return user;

    }

    @Override
    public Customer loginByToken(String token) {
        Customer customer = (Customer) EhCacheKit.getInstance().get(CommonConsts.CUST_CACHE_NAME, token);
        if (customer == null) {
            customer = customerDao.loginByToken(token);
            EhCacheKit.getInstance().put(CommonConsts.CUST_CACHE_NAME, token, customer);
        }
        return customer;
    }


}
